package com.lanou3g.springmvc.dao.impl;

import com.lanou3g.springmvc.bean.User;
import com.lanou3g.springmvc.dao.UserDao;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;

import java.util.List;

public class UserDaoImpl implements UserDao {

    private JdbcTemplate jdbcTemplate;

    /*// 在内存中模拟数据库操作
    public static List<User> userTable = new ArrayList<>();
    static {
        userTable.add(new User("张三"));
        userTable.add(new User("李四"));
        userTable.add(new User("王五"));
    }*/

    @Override
    public List<User> queryAllUser() {
        String sql = "select id,nick_name username from user";
        List<User> userList = jdbcTemplate.query(sql, new BeanPropertyRowMapper<>(User.class));
        return userList;
    }

    @Override
    public int insertUser(User user) {
        String sql = "insert into user (id, nick_name) values (?,?)";
        return jdbcTemplate.update(sql, user.getId(), user.getUsername());
    }

    @Override
    public User findById(Integer id) {
        String sql = "select id, nick_name username from user where id = ?";

//        String userName =  jdbcTemplate.queryForObject(sql, String.class, id);
//        return new User(userName);
        return jdbcTemplate.queryForObject(sql, new BeanPropertyRowMapper<>(User.class), id);
    }

    @Override
    public int deleteById(Integer id) {
        String sql = "delete from user where id = ?";
        return jdbcTemplate.update(sql, id);
    }

    @Override
    public int update(User user) {
        String sql = "update user set nick_name = ? where id = ?";
        return jdbcTemplate.update(sql, user.getUsername(), user.getId());
    }

    public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
        this.jdbcTemplate = jdbcTemplate;
    }




}
